<?php
require_once("libs/general_inc.php");

class Product extends Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {
        $sql = new sql();
        $sql->connect();
        $GENOBJ = new generalFunction();
        authentication();
        $sql = new sql();
        $sql->connect();
        $getPage = getPage();
        $this->view->getPage = $getPage[0];
        $dateTime = DateTime();
        $this->view->template = $sql->fetchAll("template", array("1" => '1'));

        if (isset($_POST['delete'])) {
            for ($i = 0; $i < count($_POST['prd_id']); $i++) {
                
                $arraydata = array(
                    "prd_status" => 2,
                );
                //$update=$sql->update('page',array("permalink"=>$permalink),array("uid"=>$_POST['editUid']));
                $update = $sql->update('tbl_product', $arraydata, array("prd_id" => $_POST['prd_id'][$i]));
                //$delete = $sql->delete('tbl_product', array("prd_id" => $_POST['prd_id'][$i]));
            }
            if ($update) {
                header("Location: " . URL . "product/?action=view&reply=ProductDeleted");
            } else {
                header("Location: " . URL . "product/?action=view&reply=PageError");
            }
        }

        if (GET('action') == 'add') {
        //    array("1" => '1')
            $categoryData = $sql->fetchAll('tbl_category', array("cat_status !" => 2));
            $this->view->categoryData = $categoryData;
            $errorMessage = array();
            $this->view->editrow = '';
            $arraydata = array();
            if (isset($_POST['submit'])) {

                $arraydata = array("prd_cat_id" => $_POST['prd_cat_id'],
                    "prd_name" => $_POST['prd_name'],
                    "prd_code" => $_POST['prd_code'],
                    "prd_short_desc" => $_POST['prd_short_desc'],
					"prd_showcase" => $_POST['prd_showcase'],
                    "prd_description" => $_POST['prd_description'],
                    "prd_price" => $_POST['prd_price'],
                    "prd_alias" => str_replace(" ", "-", strtolower($_POST['prd_name'])),
                    "prd_createdate" => date('Y-m-d h:i:s'),
                    "prd_updatedate" => date('Y-m-d h:i:s'),
                    "prd_status" => $_POST['prd_status'],
                    "LastModifyBy" => base64_decode($_COOKIE['login_user_uid']),
                );
                
              
                
                
                $allowed_ext = array(
                    'gif',
                    'jpg',
                    'jpeg',
                    'png',
                );
                if (isset($_FILES['prd_image'])){
                    $t = explode('.', basename($_FILES['prd_image']['name']));
                    $ext = strtolower(array_pop($t));
                    if (in_array($ext, $allowed_ext)) {
                            $random_digit = time();
                            $file_name = $_FILES['prd_image']['name'];
                            $new_file_name = $random_digit . $file_name;
                           // echo  BASEURL . IMAGES;exit;
                            move_uploaded_file($_FILES["prd_image"]["tmp_name"], BASEURL . IMAGES. $new_file_name);
                            $fileLocation = IMAGES . $new_file_name;
                            $arraydata["prd_image"] = $fileLocation;
                    }else{
                        $errorMessage[] = 'Please select valid image';
                        //header("Location: " . URL . "product/?action=add&reply=ProductError");
                    }
                }
               
                if(count($errorMessage) >  0){
                    
                }else{
                    $filterArray = Array("TrimElement", "htmlEntity");  
                    $filterElements = $GENOBJ->filter($arraydata, $filterArray);
                
                    $insert = $sql->insert('tbl_product', $filterElements);
                    if ($insert) {
                        header("Location: " . URL . "product/?action=view&reply=ProductCreated");
                    } else {
                        header("Location: " . URL . "product/?action=view&reply=ProductError");
                    }
                }
             }   
              $this->view->errorMessage = $errorMessage;
              $this->view->editrow = $arraydata;
        }

        if (isset($_POST['submit']) and isset($_POST['editUid'])) {

            $errorMessage = array();
            $arraydata = array("prd_cat_id" => $_POST['prd_cat_id'],
                    "prd_name" => $_POST['prd_name'],
                    "prd_code" => $_POST['prd_code'],
                    "prd_short_desc" => $_POST['prd_short_desc'],
					"prd_showcase" => $_POST['prd_showcase'],
                    "prd_description" => $_POST['prd_description'],
                    "prd_price" => $_POST['prd_price'],
                    "prd_alias" => str_replace(" ", "-", $_POST['prd_name']),
                    "prd_updatedate" => date('Y-m-d h:i:s'),
                    "prd_status" => $_POST['prd_status'],
                    "LastModifyBy" => base64_decode($_COOKIE['login_user_uid']),
                );

                
                    if ($_FILES['prd_image']['name'] != '' ){
                            $allowed_ext = array(
                                            'gif',
                                            'jpg',
                                            'jpeg',
                                            'png',
                                        );
                   // echo 'in';exit;
                    $t = explode('.', basename($_FILES['prd_image']['name']));
                    $ext = strtolower(array_pop($t));
                    if (in_array($ext, $allowed_ext)) {
                           if ($_FILES['prd_image']['name']) {
                            $random_digit = time();
                            $file_name = $_FILES['prd_image']['name'];
                            $new_file_name = $random_digit . $file_name;
                           // echo  BASEURL . IMAGES;exit;
                            move_uploaded_file($_FILES["prd_image"]["tmp_name"], BASEURL . IMAGES. $new_file_name);
                            $fileLocation = IMAGES . $new_file_name;
                            $arraydata["prd_image"] = $fileLocation;
                            $update = $sql->update('tbl_product', $arraydata, array("prd_id" => $_POST['editUid']));
                        }
                    }else{
                       // echo 'elsein';exit;
                        $errorMessage[] = 'Please select valid image';
                        //header("Location: " . URL . "product/?action=add&reply=ProductError");
                    }
                }
               
               
                if(count($errorMessage) >  0){
                    
                }else{
            //$update=$sql->update('page',array("permalink"=>$permalink),array("uid"=>$_POST['editUid']));
                    $filterArray = Array("TrimElement", "htmlEntity");  
                    $filterElements = $GENOBJ->filter($arraydata, $filterArray);
                    $update = $sql->update('tbl_product', $filterElements, array("prd_id" => $_POST['editUid']));
                    if ($update) {
                        header("Location: " . URL . "product/?action=view&reply=ProductUpdated");
                    } else {
                        header("Location: " . URL . "product/?action=view&reply=ProductError");
                    }
                }
              //  print_R($errorMessage);exit;
              $this->view->errorMessage = $errorMessage;
              $this->view->editrow = $arraydata;
           
        }
        if (GET('action') == 'view') {
            $page = (int) (GET("page") ? GET("page") : 1 );
            if (GET('search')) {
                $statement = "tbl_product as prd join tbl_category as cat on cat.cat_id = prd.prd_cat_id where prd_status!=2 and  prd_name like '%" . GET('q') . "%' Or  cat_name like '%" . GET('q') . "%' order by prd_id desc";
                $this->view->oldData = "action=" . GET('action') . "&q=" . GET('q') . "search=" . GET('q');
            } else {
                $statement = "tbl_product as prd join tbl_category as cat on cat.cat_id = prd.prd_cat_id  where prd_status!=2 order by prd_id desc";
                $this->view->oldData = "action=" . GET('action');
            }
            $limit = 50;
            $this->view->statement = $statement;
            $this->view->limit = $limit;
            $this->view->page = $page;
            $this->view->PagingNationFetch = $sql->PagingNationFetch($statement, $page, $limit);
        } 
        elseif (GET('action') == 'edit') {
            //$errorMessage = array();
            if(!isset($_POST['editUid'])){
                $errorMessage = array();
                $this->view->errorMessage = $errorMessage;
            }
            
            $categoryData = $sql->fetchAll('tbl_category', array("cat_status !" => 2));
            $this->view->categoryData = $categoryData;
            
            $this->view->editrow = $sql->fetch("tbl_product", array("prd_id" => GET('editUid')));

        }


        if (GET('reply')) {
            $this->view->noti = msg(GET('reply'));
        }

        if (checkPermission('premission_product')) {
            $this->view->render('product');
        } else {
            $this->view->render('permission_denied');
        }
    }

}

